<?php
class EmailsController extends LilcontactsAppController {

	var $name = 'Emails';
	var $helpers = array('Html', 'Form');
	var $components = array('Security', 'RequestHandler');
	
	function add($contact_id = null) {
		$this->setAction('edit', null, $contact_id);
	}

	function edit($id = null, $contact_id = null) {
		if (!empty($this->data)) {
			if ($this->Email->save($this->data)) {
				$this->Session->setFlash(__('Email has been successfully saved.', true));
				if (!empty($this->data['Email']['referer']) && $referer = base64_decode($this->data['Email']['referer'])) {
					$this->redirect($referer.'/highlight:'.$this->Email->id);
				} else if (!empty($this->data['Email']['contact_id']) && is_numeric($this->data['Email']['contact_id'])) {
					$this->redirect(array('controller'=>'contacts', 'action'=>'view', $this->data['Email']['contact_id'], 'highlight'=>$this->Email->id));
				} else {
					$this->redirect(array('controller'=>'contacts', 'action'=>'index'));
				}
			} else {
				$this->Session->setFlash(__('There are some errors in the form. Please correct all marked fields below.', true));
			}
		}
		if (empty($this->data)) {
			if (is_numeric($id) && ($this->data = $this->Email->read(null, $id))) {

			} elseif (is_numeric($contact_id) && $this->Email->Contact->findById($contact_id)) {
				$this->data['Email']['contact_id'] = $contact_id;
			} else {
				$this->error404();
				return false;
			}
			$this->data['Email']['referer'] = base64_encode($this->referer());
		}
		
		$this->set('contact_title', $this->Email->Contact->getTitle(@$this->data['Email']['contact_id']));
	}

	function delete($id = null) {
		if (!is_numeric($id) || !$this->Email->del($id)) {
			$this->error404();
		} else {
			if (!$this->RequestHandler->isAjax()) {
				$this->Session->setFlash(__('Email has been successfully deleted.', true));
			}
			$this->redirect($this->referer());
		}
	}

}
?>